import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_wildfire/flutter_wildfire.dart';
import '../components/contactItem.dart';
import '../pages/userDetail.dart';
import '../models/index.dart';
import 'package:provider/provider.dart';
import '../cmomon/userModel.dart';

class SendFriendRequest extends StatefulWidget {
  final User userData;
  SendFriendRequest({this.userData});
  @override
  _SendFriendRequestState createState() => _SendFriendRequestState();
}

class _SendFriendRequestState extends State<SendFriendRequest> {
  TextEditingController keywordController;
  bool _showCloseBtn = false;

  sendFriendRequest() async {
    final keyword = keywordController.text.trim();
    try {
          await FlutterWildfire.sendFriendRequest(widget.userData.uid, keyword);
      print('发送好友请求成功');
    } catch (e) {
      print('发送好友请求失败');
      print(e);
    } finally{
      Navigator.of(context).pop();
    }
  }

  keywordControllerChangedHandler() async {
    final keyword = keywordController.text.trim();
    this.setState(() {
      _showCloseBtn = keyword.isNotEmpty;
    });
  }

  @override
  void didChangeDependencies() {
    keywordController = TextEditingController(
        text: '我是' + Provider.of<UserModel>(context).user.displayName);

    keywordController.addListener(keywordControllerChangedHandler);
    super.didChangeDependencies();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    keywordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('朋友验证'),
        actions: <Widget>[
          MaterialButton(
            onPressed: sendFriendRequest,
            child: Text('发送'),
          )
        ],
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Text('你需要发送验证申请，等对方通过'),
            Container(
              padding: EdgeInsets.symmetric(horizontal: 12.0),
              child: Stack(
                children: <Widget>[
                  TextField(
                    autofocus: true,
                    controller: keywordController,
                    decoration: InputDecoration(),
                  ),
                  _showCloseBtn
                      ? (Positioned(
                          right: 0.0,
                          child: IconButton(
                            icon: Icon(Icons.close),
                            onPressed: () {
                              keywordController.clear();
                            },
                          ),
                        ))
                      : Container()
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
